import cv2
import numpy as np

# 灰度化，二值化
img = cv2.imread("img/rect.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# cv2.imshow("binary", binary)

# 轮廓点
contours, h = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# 图形的面积
area = cv2.contourArea(contours[0])
print(area)

# 图形的周长
arc = cv2.arcLength(contours[0], closed=True)
print(arc)

# # 轮廓近似
# epsilon = 0.08 * arc
# approx = cv2.approxPolyDP(contours[0], epsilon, True)
# cv2.polylines(img, [approx], isClosed=True, color=(0, 255, 0),thickness=2)
# cv2.imshow("img", img)
# cv2.waitKey(0)

# 直角矩形
x1, y1, w, h = cv2.boundingRect(contours[0])
x2, y2 = x1 + w, y1 + h
cv2.rectangle(img, (x1, y1), (x2, y2), color=(0, 255, 0), thickness=2)
# 近似矩形(包裹图像的最小矩形)
result = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(result).astype(np.int32)
cv2.drawContours(img, [box], 0, color=(255, 0, 0), thickness=2)

# 外接圆
(cx, cy), radius = cv2.minEnclosingCircle(contours[0])
cx = int(cx)
cy = int(cy)
radius = int(radius)
cv2.circle(img, (cx, cy), radius, color=(255, 255, 0), thickness=2)
cv2.imshow("img", img)
cv2.waitKey(0)
